import 'dart:collection';
import 'dart:convert';

import 'package:bruno/bruno.dart';
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:sph_driver/AppConfig/LocalStorage.dart';

import '../AppConfig/CityLIstData.dart';
import '../AppConfig/Config.dart';
import '../AppConfig/StringEncapsulation.dart';
import '../http/api.dart';
import '../l10n/messages.dart';
import 'UpEmptyLine.dart';

class EditLine extends StatefulWidget {
  const EditLine({super.key, required this.dataMap});
  final Map dataMap;
  @override
  State<EditLine> createState() => _EditLineState();
}

class _EditLineState extends State<EditLine> {
  late String startCity="+ 选择";
  late String endCity="+ 选择";
  List chooseStartList=[];
  List chooseEndList=[];
  int startType=-1;
  int endType=-1;
  List startNameList=[];
  List endNameList=[];
  List startCodeList=[];
  List endCodeList=[];
  String startName="";
  String endName="";

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    print(widget.dataMap);
    startName=widget.dataMap['loadPlace']['province']+" "+widget.dataMap['loadPlace']['city']+" "+widget.dataMap['loadPlace']['county'];
    endName=widget.dataMap['unloadPlace']['province']+" "+widget.dataMap['unloadPlace']['city']+" "+widget.dataMap['unloadPlace']['county'];
    startNameList=[widget.dataMap['loadPlace']['province'],widget.dataMap['loadPlace']['city'],widget.dataMap['loadPlace']['county']];
    endNameList=[widget.dataMap['unloadPlace']['province'],widget.dataMap['unloadPlace']['city'],widget.dataMap['unloadPlace']['county']];
    startCity=widget.dataMap['loadPlace']['city'];
    startCodeList.add(widget.dataMap['loadPlace']['areaCode']);
    endCodeList.add(widget.dataMap['unloadPlace']['areaCode']);
    if(widget.dataMap['loadPlace']['county']!="")
    startCity=widget.dataMap['loadPlace']['county'];
    endCity=widget.dataMap['unloadPlace']['city'];
    if(widget.dataMap['unloadPlace']['county']!="")
      endCity=widget.dataMap['unloadPlace']['county'];
  }
  @override
  Widget build(BuildContext context) {
    final screenSize = MediaQuery.of(context).size;
    return Scaffold(
      appBar: AppBar(
        title:Text( "修改路线",style: TextStyle(fontWeight: FontWeight.w300,fontSize: 16.sp),),
        backgroundColor: Colors.white,
        centerTitle: true,
        leading: IconButton(
          icon: Icon(Icons.arrow_back_ios, color: Colors.black),
          onPressed: () => Navigator.of(context).pop(),
        ),
        // actions: [
        //
        //   Badge(
        //     label:Text("1"),
        //     child:GestureDetector(
        //       child: Row(
        //         children: [
        //
        //           Image.asset("lib/Images/RoadLine/消息icon.png",width: 16.w,height: 16.h,),
        //           SizedBox(width: 10.w,),
        //         ],
        //       ),
        //       onTap: (){
        //
        //       },
        //     ),
        //
        //
        //   ),
        // ],
      ),
      body: ListView(
        children: [
          SizedBox(height: 8.h,),
          Container(
            height: 40.h,
            margin: EdgeInsets.only(right: 8.w,left: 8.w),

            decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.all(Radius.circular(10))),
            child:Row(
              children: [

                SizedBox(width: 8.w,),
                Container(
                  constraints: BoxConstraints(
                    maxWidth:screenSize.width/2.4, // 限制文本最大宽度
                  ),
                  child:  Text(startName,
                    maxLines: 1, // 设置显示的最大行数
                    overflow: TextOverflow.ellipsis, // 超出部分使用省略号表示
                    style: TextStyle(color: Colors.black,fontWeight: FontWeight.w600,fontSize: 14.sp),),

                ),


                Icon(Icons.arrow_forward,color: Colors.black,),
                Container(
                  constraints: BoxConstraints(
                    maxWidth:screenSize.width/2.4, // 限制文本最大宽度
                  ),
                  child: Text(endName,
                    maxLines: 1, // 设置显示的最大行数
                    overflow: TextOverflow.ellipsis, // 超出部分使用省略号表示
                    style: TextStyle(color: Colors.black,fontWeight: FontWeight.w600,fontSize: 14.sp),),

                ),
              ],
            ),
          ),
          SizedBox(height: 6.h,),
          Container(
            height: 230.h,
            decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.all(Radius.circular(10))),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                SizedBox(height: 8.h,),
                Row(
                  children: [
                    SizedBox(width: 18.w,),
                    Image.asset("lib/Images/RoadLine/绿色圆圈.png",height: 9.h,width: 9.w,),
                    SizedBox(width: 4.w,),
                    Text("请选择装货地",style: TextStyle(color: Colors.black,fontWeight: FontWeight.w600,fontSize: 14.sp),),
                    // Text("(最多3个)",style: TextStyle(color: Colors.black,fontSize: 14.sp),),
                  ],
                ),
                SizedBox(height: 8.h,),
                GestureDetector(
                  child:  Container(
                    margin: EdgeInsets.only(left: 18.w),
                    padding: EdgeInsets.only( right: 10.w,left: 10.w,top: 5.h,bottom: 5.h),
                    width:70.w,
                    height: 25.h,
                    decoration: BoxDecoration(
                        color:startCity!="+ 选择"?Color.fromRGBO(251, 236, 228, 1) :Color.fromRGBO(240, 240, 240, 1),
                        borderRadius: BorderRadius.all(Radius.circular(5))),
                    child:Center(
                      child:   Text(startCity,style: TextStyle(color: startCity!="+ 选择"?MyColors.themeColor: Colors.black,fontSize: 13.sp,fontWeight: FontWeight.w400),),
                    ),

                  ),
                  onTap: ()async{

                    final result = await showModalBottomSheet(
                        context: context,
                        isScrollControlled: true,

                        builder: (BuildContext context) {
                          return ChooseAddressSheet(addressType: 1,

                          );
                        }
                    );
                    if (result != null) {
                      setState(() {

                        startCity=result[0];
                        startType=result[1];
                        startNameList=[result[2],result[3],result[4]];
                        print(startNameList);
                        for (String cityName in startNameList) {
                          String cityCode = getCityCodeByName(MyCityListData.CityList, cityName);
                          if (cityCode != "") {
                            print('$cityName 的城市编码为：$cityCode');
                            cityCode=getCodeResult(cityCode);
                            startCodeList.add(cityCode);

                          } else {
                            print('未找到城市 $cityName');
                          }
                        }
                      });
                    }


                  },
                ),
                SizedBox(height: 8.h,),
                Container(
                  margin: EdgeInsets.only(right: 8.w),
                  height: 1.h,color: Color.fromRGBO(248, 248, 248, 1),),
                SizedBox(height: 8.h,),
                Row(
                  children: [
                    SizedBox(width: 18.w,),
                    Image.asset("lib/Images/RoadLine/红色圆圈.png",height: 9.h,width: 9.w,),
                    SizedBox(width: 4.w,),
                    Text("请选择卸货地",style: TextStyle(color: Colors.black,fontWeight: FontWeight.w600,fontSize: 14.sp),),
                  ],
                ),
                SizedBox(height: 8.h,),
                GestureDetector(
                  child:  Container(
                    margin: EdgeInsets.only(left: 18.w),
                    padding: EdgeInsets.only( right: 10.w,left: 10.w,top: 5.h,bottom: 5.h),
                    width:70.w,
                    height: 25.h,
                    decoration: BoxDecoration(
                        color:endCity!="+ 选择"?Color.fromRGBO(251, 236, 228, 1) :Color.fromRGBO(240, 240, 240, 1),
                        borderRadius: BorderRadius.all(Radius.circular(5))),
                    child:Center(
                      child:   Text(endCity,style: TextStyle(color: endCity!="+ 选择"?MyColors.themeColor: Colors.black,fontSize: 13.sp,fontWeight: FontWeight.w400),),
                    ),
                  ),
                  onTap: ()async{

                    final result = await showModalBottomSheet(
                        context: context,
                        isScrollControlled: true,

                        builder: (BuildContext context) {
                          return ChooseAddressSheet(addressType: 2,

                          );
                        }
                    );
                    if (result != null) {
                      setState(() {
                        endCity=result[0];
                        endType=result[1];
                        endNameList=[result[2],result[3],result[4]];
                        print(endNameList);
                        for (String cityName in endNameList) {
                          String cityCode = getCityCodeByName(MyCityListData.CityList, cityName);
                          if (cityCode != "") {
                            print('$cityName 的城市编码为：$cityCode');
                            cityCode=getCodeResult(cityCode);
                            endCodeList.add(cityCode);

                          } else {
                            print('未找到城市 $cityName');
                          }
                        }
                      });
                    }



                  },
                ),
                SizedBox(height:38.h ,),
                Container(
                    height: 35.h ,
                    margin: EdgeInsets.only(left: 30.w,right: 30.w),
                    decoration: BoxDecoration(
                        color: Color.fromRGBO(231, 112, 27, 0.85),
                        borderRadius: BorderRadius.all(Radius.circular(30))),

                    width: double.infinity,


                    child: TextButton(
                      child: Text("修改",style: TextStyle(color: Colors.white,fontSize: 14.sp,fontWeight: FontWeight.w600),),

                      onPressed: () async {
                        if(startNameList.isEmpty){
                          BrnToast.show("请选择装货城市", context);
                        }else if(endNameList.isEmpty){
                          BrnToast.show("请选择卸货城市", context);
                        }else  if(startNameList[1]==""){
                          BrnToast.show("装货地请至少选择至市", context);
                        }else if(endNameList[1]==""){
                          BrnToast.show("卸货地请至少选择至市", context);
                        }else{
                          String? drvId =await UserIdManager.getUserID();
                          ApiManager.postData(
                            context,
                            'api/goods/driver/route/edit',
                            {
                              "id":widget.dataMap['id'],
                              "loadPlace": {
                                "province": startNameList[0],
                                "city": startNameList[1],
                                "county": startNameList[2],
                                "areaCode": startCodeList.last,
                              },
                              "unloadPlace": {
                                "province": endNameList[0],
                                "city": endNameList[1],
                                "county": endNameList[2],
                                "areaCode":endCodeList.last,
                              },
                            },
                                (responseData) {
                              setState(() {
                                BrnToast.show("添加成功", context);
                                Navigator.pop(context,"success");
                              });
                            },
                          );
                        }
                      },
                    )
                ),
              ],
            ),
          ),

        ],
      ),
    );
  }
}
